package com.cxx.purchasecharge.dal.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.cxx.purchasecharge.core.model.AuthorityResource;
import com.cxx.purchasecharge.dal.AuthorityResourceDao;

@Repository ("authorityResourceDao")
public class AuthorityResourceDaoImpl implements AuthorityResourceDao
{
    private static final Logger logger = Logger.getLogger (AuthorityResourceDaoImpl.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List <AuthorityResource> findByAuthorityName (String authorityName)
    {
        logger.debug ("Find AuthorityResourceModel by authorityName: " + authorityName);
        if (StringUtils.isNotBlank (authorityName))
        {
            String sql = "select a.name as authority, r.name as resourceName, r.value as resourceValue from pc_authority a, pc_resource r, pc_authority_resource ar where a.id=ar.authority_id and r.id=ar.resource_id and a.name=?1";
            Query query = entityManager.createNativeQuery (sql, AuthorityResource.class);
            query.setParameter (1, authorityName);
            @SuppressWarnings ("unchecked")
            List <AuthorityResource> authorityResources = query.getResultList ();
            return authorityResources;
        }
        return null;
    }
}
